package com.jokul.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.jokul.model.Account;

/**
 *@author: jokul
 *@2013-3-15 下午4:29:24
 */

public class AccountDaoImpl implements AccountDao {

	private DataSource dataSource;

	public AccountDaoImpl(DataSource dataSource) {
		super();
		this.dataSource = dataSource;
	}

	@Override
	public boolean isUserExisted(Account account) {
		Connection connection = null;
		PreparedStatement statement = null;
		String sql = "select count(*) from account where name = ?";
		
		try {
			connection = dataSource.getConnection();
			statement = connection.prepareStatement(sql);
			statement.setString(1, account.getName());
			ResultSet set = statement.executeQuery();
			if(set.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(statement != null) {
					statement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public int addAccount(Account account) {
		Connection connection = null;
		PreparedStatement statement = null;
		try {
			connection = dataSource.getConnection();
			statement = connection.prepareStatement(
					"INSERT INTO ACCOUNT (NAME,PASSWORD,EMAIL) VALUES (?,?,?)");
			statement.setString(1, account.getName());
			statement.setString(2, account.getPassword());
			statement.setString(3, account.getEmail());
			return statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(statement != null) {
					statement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public Account getAccount(Account account) {
		Connection connection = null;
		PreparedStatement statement = null;
		String sql = "select password,email from account where name = ?";
		
		try {
			connection = dataSource.getConnection();
			statement = connection.prepareStatement(sql);
			statement.setString(1, account.getName());
			ResultSet set = statement.executeQuery();
			if(set.next()) {
				return new Account(account.getName(), set.getString(1), set.getString(2));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(statement != null) {
					statement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	
}
